package com.example.qu_tao.View;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.example.qu_tao.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

public class XinwenFragment extends Fragment {
    public static final String URL_DETAILS = "file:///android_asset/page/xinwen.html";
    private WebView mWebView;
    private Button mButton;
    private static final int REQUEST_PERMISSION_READ_EXTERNAL_STORAGE = 1;
    private static final int REQUEST_CODE_PICK_IMAGE = 2;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fargment_xinwen, container, false);
        initView(view);
        initListener();
        return view;
    }

    private void initView(View view) {
        mWebView = view.findViewById(R.id.webview);
        mButton = view.findViewById(R.id.button);

        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true); // 允许通过file URL访问文件

        mWebView.addJavascriptInterface(new WebAppInterface(), "myInterface");
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (url.contains("xinwen.html")) {
                    loadNewsFromDatabase();
                }
            }
        });
        mWebView.loadUrl(URL_DETAILS);
    }

    @android.annotation.SuppressLint("Range")
    private void loadNewsFromDatabase() {
        Uri uri = Uri.parse("content://com.example.qu_tao.provider/news");
        Cursor cursor = getActivity().getContentResolver().query(
                uri,
                null,
                null,
                null,
                "publish_time ASC");
        if (cursor != null && cursor.moveToFirst()) {
            try {
                JSONArray newsArray = new JSONArray();
                do {
                    JSONObject newsItem = new JSONObject();
                    newsItem.put("title", cursor.getString(cursor.getColumnIndex("title")));
                    newsItem.put("time", cursor.getString(cursor.getColumnIndex("publish_time")));
                    newsItem.put("views", cursor.getInt(cursor.getColumnIndex("views")));
                    newsItem.put("image", cursor.getString(cursor.getColumnIndex("image_path")));
                    newsItem.put("content", cursor.getString(cursor.getColumnIndex("content")));
                    newsArray.put(newsItem);
                } while (cursor.moveToNext());
                String jsCode = "javascript:loadNewsFromDatabase('" + newsArray.toString() + "')";
                mWebView.loadUrl(jsCode);
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                cursor.close();
            }
        }
    }

    private void initListener() {
        mButton.setOnClickListener(v -> {
            String title = "这个是新的标题";
            mWebView.loadUrl("javascript:setTitle('" + title + "')");
        });
    }

    public class WebAppInterface {
        @JavascriptInterface
        public void onTitleUpdate(boolean showToast, String newTitle) {
            if (showToast) {
                showToast("新标题:" + newTitle);
            }
        }

        @JavascriptInterface
        public void goBack(boolean showToast, String currentTitle) {
            if (showToast) {
                showToast("当前标题:" + currentTitle);
            }
            if (getActivity() != null) {
                getActivity().finish();
            }
        }

        @JavascriptInterface
        public String saveImage(String base64Image) {
            try {
                // 解码Base64图片数据
                String pureBase64Encoded = base64Image.substring(base64Image.indexOf(",") + 1);
                byte[] decodedBytes = Base64.getDecoder().decode(pureBase64Encoded);

                // 保存图片到应用目录
                File storageDir = getActivity().getExternalFilesDir(android.os.Environment.DIRECTORY_PICTURES);
                if (!storageDir.exists()) {
                    storageDir.mkdirs();
                }
                File imageFile = new File(storageDir, "news_image_" + System.currentTimeMillis() + ".jpg");
                FileOutputStream fos = new FileOutputStream(imageFile);
                fos.write(decodedBytes);
                fos.close();

                // 返回文件URI路径（使用file://协议）
                return Uri.fromFile(imageFile).toString();
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        }

        @JavascriptInterface
        public void getNewsContent(String title) {
            Uri uri = Uri.parse("content://com.example.qu_tao.provider/news");
            Cursor cursor = getActivity().getContentResolver().query(
                    uri,
                    new String[]{"content"},
                    "title = ?",
                    new String[]{title},
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                @android.annotation.SuppressLint("Range") String content = cursor.getString(cursor.getColumnIndex("content"));
                cursor.close();
                String jsCode = "javascript:setNewsContent('" + content.replace("'", "\\'") + "')";
                mWebView.post(() -> mWebView.loadUrl(jsCode));
            }
        }

        @JavascriptInterface
        public boolean saveNewsToDatabase(String newsJson) {
            try {
                JSONObject newsData = new JSONObject(newsJson);
                android.content.ContentValues values = new android.content.ContentValues();
                values.put("title", newsData.getString("title"));
                values.put("content", newsData.getString("content"));
                values.put("image_path", newsData.getString("image"));
                values.put("publish_time", newsData.getString("time"));
                values.put("views", newsData.getInt("views"));
                Uri uri = Uri.parse("content://com.example.qu_tao.provider/news");
                Uri insertedUri = getActivity().getContentResolver().insert(uri, values);
                return insertedUri != null;
            } catch (JSONException e) {
                e.printStackTrace();
                return false;
            }
        }

        @JavascriptInterface
        public void openGallery() {
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
                    != android.content.pm.PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_PERMISSION_READ_EXTERNAL_STORAGE);
            } else {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
            }
        }

        @SuppressLint("Range")
        @JavascriptInterface
        public String getNewsImagePath(String title) {
            Uri uri = Uri.parse("content://com.example.qu_tao.provider/news");
            ContentResolver contentResolver = getActivity().getContentResolver();
            Cursor cursor = contentResolver.query(uri, new String[]{"image_path"}, "title = ?", new String[]{title}, null);
            String imagePath = null;
            if (cursor != null && cursor.moveToFirst()) {
                imagePath = cursor.getString(cursor.getColumnIndex("image_path"));
                cursor.close();
            }
            return imagePath;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_READ_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
            } else {
                showToast("没有读取存储权限，无法选择图片");
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            try {
                // 将图片转换为Base64编码
                String base64Image = uriToBase64(selectedImage);
                String jsCode = "javascript:setImagePath('" + base64Image + "')";
                mWebView.post(() -> mWebView.loadUrl(jsCode));
            } catch (IOException e) {
                e.printStackTrace();
                showToast("图片加载失败");
            }
        }
    }

    // 将Uri转换为Base64字符串
    private String uriToBase64(Uri imageUri) throws IOException {
        InputStream inputStream = getActivity().getContentResolver().openInputStream(imageUri);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        inputStream.close();
        return "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(bytes);
    }

    private void showToast(String message) {
        Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
    }
}